/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <pthread.h>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* reserve(ListNode* head1)
    {
        //翻转这个链表
        ListNode* pre = nullptr;
        ListNode* cur = head1;
        ListNode* next = head1;
        while(cur)
        {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        //首先翻转两个链表，然后模拟加法即可
        head1 = reserve(head1);
        head2 = reserve(head2);
        //模拟加法
        ListNode* cur1 = head1;
        ListNode* cur2 = head2;
        ListNode* newhead = new ListNode(0);
        ListNode* cur = newhead;
        int cnt = 0;//这是进位
        while(cur1&&cur2)
        {
            int sum = cur1->val+cur2->val+cnt;
            cnt = sum/10;
            sum = sum%10;
            cur->next = new ListNode(sum);
            cur = cur->next;
            cur1 = cur1->next;
            cur2 = cur2->next;
        }
        //处理不为空的那个链表
        while(cur1)
        {
            int sum = cur1->val+cnt;
            cnt = sum/10;
            sum = sum%10;
            cur->next = new ListNode(sum);
            cur = cur->next;
            cur1 = cur1->next;
        }
        while(cur2)
        {
            int sum = cur2->val+cnt;
            cnt = sum/10;
            sum = sum%10;
            cur->next = new ListNode(sum);
            cur = cur->next;
            cur2 = cur2->next;
        }
        if(cnt!=0)
        {
            cur->next = new ListNode(cnt);
        }
        ListNode* ret = reserve(newhead->next);   
        return ret;
    }
};